<?php
namespace Rainrock\Framework\Controller;


use Rainrock\Framework\kernel\core\Controller;
use Rainrock\Framework\kernel\core\Module;
use Rainrock\Framework\kernel\base\Request;
use Rainrock\Framework\kernel\base\CLog;
use Rainrock\Framework\kernel\base\Rock;
use Rainrock\Framework\kernel\base\Base;
use Rainrock\Framework\kernel\base\File;
use Rainrock\Framework\kernel\base\Jiami;
use Rainrock\Framework\kernel\base\Auth;
use Rainrock\Framework\kernel\db\DB;

/**
*	数据库操作
*/
class DatabaseController extends Controller{
	
	public function indexAction()
	{
		$str   = 'php index.php database/update num=all [installupdate database]';
		CLog::back($str);
	}
	
	/**
	*	更新或者创建数据库
	*/
	public function updateAction()
	{
		$num	= Request::param('num');
		$group	= Request::param('group');
		$zhu	= Request::param('zhu');
		if(!$num && !$group)return 'plase input params(num/group)';
		
		$db	  		= DB::createDb();
		$alltable 	= $db->getAlltable();		
		CLog::show('--- updatedb start('.$db->getDbtype().') ---');
		$count 		= 0;
		if($num == 'all' || $group){
			$groups		= Module::getList();
			foreach($groups as $gs=>$als){
				if(!$group || ($group && Rock::contain(','.$group.',', ','.$gs.','))){
					foreach($als as $nu1){
						$info = Module::get($nu1, $gs);
						if($info){
							$info->updateTable($db, $alltable);
							CLog::show('--- '.$info->getName().'('.$info->getTablename().') update success ---');
							$count++;
						}
					}
				}
			}
		}
		if($num && $num != 'all'){
			$numa = explode(',', $num);
			foreach($numa as $nu1){
				$info = Module::get($nu1, $zhu);
				if($info){
					$info->updateTable($db, $alltable);
					CLog::show('--- '.$info->getName().'('.$info->getTablename().') update success ---');
					$count++;
				}
			}
		}
		CLog::show('--- updatedb end tablecount('.$count.') ---');
	}
	
	/**
	*	导出数据库，请用cli模式
	*	php index.php database/daochu
	*/
	public function daochuAction()
	{
		$db = $this->getDb();
		if($db->getDbtype()=='sqlite'){
			CLog::show('--- sqlite not run daochu ---');
			return;
		}
		$isdown = false;
		if(PHP_SAPI != 'cli'){
			$this->getAuth();
			if(Auth::$TYPE != 2){
				CLog::error('plase use cli input:php '.ROOT_PATH.'/index.php database/daochu');
				return;
			}else{
				$isdown = true;
			}
		}
		$alltable 	= $db->getAlltable();
		$paths 	 	= ''.UPDIR.'/data/'.$db->getDbbase().'_'.date('YmdHis').'_'.Jiami::getRandmd5().'.sql';
		Rock::createDir($paths, ROOT_PATH);
		$qian 	 	= $db->getDbperfix();
		$nobeifne	= array(''.$qian.'syslog', ''.$qian.'systoken');
		$path		= ''.ROOT_PATH.'/'.$paths.'';
		$file 		= @fopen($path, 'ab+');
		if($file){
			foreach($alltable as $tabs){
				$sqla 	 	= $db->getalls('show create table `'.$tabs.'`');
				$createsql	= $sqla[0]['Create Table'];
				$createsql	= str_replace('`'.$tabs.'`', 'IF NOT EXISTS `'.$tabs.'`', $createsql).";\n";
				if(!in_array($tabs, $nobeifne)){
					$strstr	 = "\nDROP TABLE IF EXISTS `$tabs`;\n";
					$strstr	.= $createsql;
					fwrite($file,$strstr);
					$rows  	= $db->getalls('select * from `'.$tabs.'`', function($rs, $cans){
						$vstr = '';
						foreach($rs as $k1=>$v1){
							if(!Rock::isempt($v1))$v1 = str_replace("\n",'\n', $v1);
							$v1 = ($v1===null) ? 'NULL' : "'$v1'";
							$vstr.=",$v1";
						}
						$vstr 	= substr($vstr,1);
						$tabs	= $cans['tabs'];
						$strstr	= "INSERT INTO `$tabs` VALUES($vstr);\n";
						fwrite($cans['file'], $strstr);
						return $vstr;
					}, array(
						'file' 	=> $file,
						'tabs'	=> $tabs
					));
					CLog::show('--- '.$tabs.' success count('.count($rows).') ---');
				}else{
					fwrite($file, $createsql);
					CLog::show('--- '.$tabs.' break ---');
				}
			}
			fclose($file);
			CLog::show('--- database success count('.count($alltable).') '.$path.'');
			if($isdown)CLog::show('--- <a href="'.$paths.'">[down]</a>');
		}else{
			CLog::show('--- Permission denied write '.$path.'');
		}
	}
}